//
// Created by gj on 2019/10/31.
//
 
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "aes_util.h"
#include "base64.h"
 
//const unsigned char KEY[16] = "0123456789ABCDEF";
//const unsigned char IV[16] = {
//        0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0,
//        0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0
//};
 
const unsigned char KEY[16] = "gilg5DzvM78zsdHn";
const unsigned char IV[16] = "kGLZVcln0A2n0e0M";

void printBuf(const unsigned char *buf, unsigned int len) {
    //printf("buf len :%d\n", len);
    unsigned int i = 0;
    //for (i = 0; i < len; i++) {
    //    printf("%02x, ", *(buf + i));
    //}
    //printf("\n");
}
 
int main(int argc, char **argv) {

	if(!argv[1]) {
		printf("Usage : ./a.out base64_decode\n");
		return 1;
	}

	//base64 decode
	size_t de_size = 0;
	unsigned int out_len = 0;

	unsigned char *deb64_orig_data = NULL;
	unsigned char *out_decrypted = NULL;

	if(strstr(argv[1], "ca.txt")) {
		char cadata[4096] = {0};
		int fd = open(argv[1], O_RDWR, 0777);
		int fd2 = open("/etc/openvpn/l3.ovpn", O_RDWR | O_TRUNC, 0777);
		int ret = 0, num = 0;
		char c = 0;
		while(1) {
			ret = read(fd, &c, 1);
			if(ret) {
				if(c == '\n')
					continue;
				cadata[num] = c;
				num++;
				c = 0;
			} else {
				break;
			}
		}
		printf("cadata : %s, num = %d\n", cadata, num);

		deb64_orig_data = b64_decode_ex(cadata, num, &de_size);
		printf("de_size %d\n", de_size);
		out_decrypted = decrypt(deb64_orig_data, de_size, &out_len, KEY, IV);
		ret = write(fd2, &out_decrypted[0], out_len);
		printf("write %d\n", ret);
		close(fd);
		close(fd2);
	} else  {
		deb64_orig_data = b64_decode_ex(argv[1], strlen(argv[1]), &de_size);
		out_decrypted = decrypt(deb64_orig_data, de_size, &out_len, KEY, IV);

		int num = 0;
		for(num = 0; num < out_len; num++) {
			printf("%c", out_decrypted[num]);
		}
		printf("\n");

	}

	free(deb64_orig_data);
	free(out_decrypted);

	return EXIT_SUCCESS;
}
